<?php
/**
 * Created by PhpStorm.
 * 网易七鱼-客服系统对接
 * User: caicm
 * Date: 2017/8/11
 * Time: 9:26
 */

namespace SDXApi\Controller;


use Think\Controller;

class YukfController extends Controller {
    protected $appid;
    protected $appsecret;
    protected $token;
    protected $host;

    protected function _initialize() {
        header("Access-Control-Allow-Headers: origin, x-csrftoken, content-type, accept, x-auth-code, X-App-Id, X-Token");
        header("Access-Control-Allow-Method: POST, GET, OPTIONS");
        header("Access-Control-Allow-Origin: *");

        $this->appid = '2017887';
        $this->appsecret = 'tWx41i08EuKzxmDqdfqdqSXsAhld1jD6';
        $this->token = '3MlZtTIDntA3GB12zysVbrOqkkfNDM4b';
        $this->host = 'http://w.shidexian.com/admin/';

    }

    /**
     * 调起web客服页面
     * Created By caicm
     */
    public function page_web(){

        $uid = I('get.uid');            //用户id
        $source = I('get.source');      //来源 h5 ios android
        $version = I('get.version');    //版本号
        $time = I('get.time');          //访问时间戳
        $type = I('get.type');          //访问类型 1-商品详情 2-订单详情 3-客服界面
        $goods_id = I('get.goods_id');  //商品id type等于1时不能为空
        $order_id = I('get.order_id');  //订单id type等于2时不能为空
        $sing = I('get.sing');          //签名 md5(uid+source+version+time+type+key); key = L9hPVBRK4wSPZzMAVRDO6egVSJt0ecvn;

        $key = 'L9hPVBRK4wSPZzMAVRDO6egVSJt0ecvn';

        if (empty($source) || empty($time) || empty($type) || empty($sing)){
            die('参数有误');
        }
        if (!in_array($source, array('h5', 'ios', 'android'))){
            die('source参数有误');
        }
        if (time() - $time > 60*60){
            die('访问超时');
        }
        //echo md5($uid . $source . $version .$time .$type .$key);

        if ($sing != md5($uid . $source . $version .$time .$type .$key)){
            die('签名有误');
        }


        //用户信息
        $user_info = M('users as u')
            ->field('w.openid,w.nickname,w.sex,u.user_id,u.user_name,u.mobile_phone,u.reg_time,u.email')
            ->join('left join sdx_wechat_user as w on w.ect_uid=u.user_id')
            ->where(array('u.user_id'=>$uid))
            ->find();

        if(empty($user_info)){
            die('用户不存在');
        }

        $user_info['reg_time'] = local_date('Y-m-d H:i:s', $user_info['reg_time']);
        if($user_info['sex'] == 1){
            $user_info['sex'] = '男';
        }elseif ($user_info['sex'] == 2){
            $user_info['sex'] = '女';
        }else{
            $user_info['sex'] = '未知';
        }

        switch ($type){

            case 1:
                //商品详情
                if(empty($goods_id)) {
                    die('商品id不能为空');
                }

                $goods_info = M('goods')->field('goods_name,goods_img,goods_sn,goods_id')->find($goods_id);
                if(empty($goods_info)) {
                    die('商品不存在');
                }

                $this->assign('goods_info', $goods_info);
                $type_name = '商品详情';
                break;

            case 2:
                //订单详情
                if(empty($order_id)) {
                    die('订单id不能为空');
                }

                $order_info = M('order_info')->field('order_sn,order_id')->find($order_id);
                if(empty($order_info)) {
                    die('订单不存在');
                }

                $this->assign('order_info', $order_info);
                $type_name = '订单详情';
                break;

            case 3:
                //客服界面
                $type_name = '客服界面';
                break;

            default:
                die('type参数有误');
                break;
        }

        $this->assign('source', $source . ($version ? "版本号：{$version}" : ''));
        $this->assign('type_name', $type_name);

        $this->assign('openid', $user_info['user_id']);
        $this->assign('name', $user_info['nickname']);
        $this->assign('mobile', $user_info['mobile_phone'] ? $user_info['mobile_phone'] : 0);

        $confing = array(
            array(
                'key' => 'real_name',
                'value' => $user_info['nickname']
            ),
            array(
                'key' => 'mobile_phone',
                'value' => $user_info['mobile_phone'] ? $user_info['mobile_phone'] : 0
            ),
            array(
                'key' => 'email',
                'value' => $user_info['email']
            ),
//            array(
//                'key' => 'staffid',
//                'value' => 56042
//            ),
            array(
                'index' => 0,
                'key' => 'user_id',
                'label' => '用户id',
                'value' => $user_info['user_id'],
                'href' => $this->host.'users.php?act=list&keyword='.$user_info['user_name']
            ),
            array(
                'index' => 1,
                'key' => 'nickname',
                'label' => '微信昵称',
                'value' => $user_info['nickname']
            ),
            array(
                'index' => 2,
                'key' => 'sex',
                'label' => '性别',
                'value' => $user_info['sex']
            ),
            array(
                'index' => 3,
                'key' => 'reg_time',
                'label' => '注册日期',
                'value' => $user_info['reg_time']
            ),
            array(
                'index' => 5,
                'key' => 'source',
                'label' => '来源',
                'value' => $source
            )
        );

        if($type == 1){
            $confing[] = array(
                'index' => 4,
                'key' => 'test_msg',
                'label' => '访问页面',
                'value' => $goods_info['goods_name'],
                'href' => $this->host.'goods.php?act=edit&goods_id='.$goods_info['goods_id']
            );
        }
        elseif($type == 2){
            $confing[] = array(
                'index' => 4,
                'key' => 'test_msg',
                'label' => '访问页面',
                'value' => $order_info['order_sn'],
                'href' => $this->host. 'order.php?act=info&order_id='.$order_info['order_id'],
            );
        }elseif ($type == 3){
            $confing[] = array(
                'index' => 4,
                'key' => 'test_msg',
                'label' => '访问页面',
                'value' => '客服界面',
            );
        }

        // $array = json_encode($confing);
        // echo decodeUnicode(json_encode($confing));;
//print_r(json_encode($confing));

        $code = json_encode($confing);
        $confing =  preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $code);

        $this->assign('confing', $confing);
        $this->assign('host', $this->host);

        $this->display();



    }


    /**
     * 获取token
     * Created By caicm
     */
    public function get_token(){
        $appid = I('get.appid');
        $appsecret = I('get.appsecret');

        $this->check_token($appid, $appsecret);

        //write_log("appid:{$appid},appsecret:{$appsecret}" , 'yukf');

        $data = array(
            'rlt' => 0,
            'token' => $this->token,
            'expires' => 7200000
        );

        $this->return_json($data);

    }

    /**
     *  呼叫中心获取电话用户信息
     * Created By caicm
     */
    public function get_call_user_info(){
        $json = file_get_contents('php://input');
        $data = json_decode($json, true);

        $phone = $data['userid'];  //用户唯一标识 phone
        $appid = $data['appid'];
        $token = $data['token'];

        $this->check_token($appid, '', $token);

        //用户信息
        $user_info = $this->get_call_user($phone);
        $return_data = $this->get_user_data($user_info);
        $this->return_json($return_data);
    }

    /**
     * 获取用户信息
     * Created By caicm
     */
    public function get_user_info(){
        $json = file_get_contents('php://input');
        $data = json_decode($json, true);

        //write_log($json , 'yukf');

        $openid = $data['userid'];  //用户唯一标识 openid
        $appid = $data['appid'];
        $token = $data['token'];

        $this->check_token($appid, '', $token);

        //用户信息
        $user_info = $this->find_user_info($openid);
        $return_data = $this->get_user_data($user_info);
        $this->return_json($return_data);

    }



    /**
     * 呼叫中心获取用户订单信息
     * Created By caicm
     */
    public function get_call_order(){
        $json = file_get_contents('php://input');
        $data = json_decode($json, true);

        $phone = $data['userid'];  //用户唯一标识 phone
        $appid = $data['appid'];
        $token = $data['token'];
        $from = $data['from'];      //请求返回订单列表的偏移量，与count配合使用实现分页。
        $count = $data['count'];    //请求返回订单的最大数量。与from配合使用实现分页

        $this->check_token($appid, '', $token);
        $user_info = $this->get_call_user($phone);
        $return_data = $this->get_order_list($user_info['user_id'], $from);
        $this->return_json($return_data);
    }

    /**
     * 获取订单信息
     * Created By caicm
     */
    public function get_order(){
        $json = file_get_contents('php://input');
        $data = json_decode($json, true);

        $openid = $data['userid'];  //用户唯一标识 openid
        $appid = $data['appid'];
        $token = $data['token'];
        $from = $data['from'];      //请求返回订单列表的偏移量，与count配合使用实现分页。
        $count = $data['count'];    //请求返回订单的最大数量。与from配合使用实现分页

        $this->check_token($appid, '', $token);
        $return_data = $this->get_order_list($openid, $from);
        $this->return_json($return_data);

    }

    /**
     * 获取订单商品列表
     * Created By caicm
     * @param $order_id
     * @return mixed
     */
    public function get_order_goods($order_id){
        return M('order_goods')
            ->where(array('order_id' => $order_id))
            ->field('goods_id,goods_name,goods_sn,goods_number,goods_price')
            ->select();
    }

    /**
     * 用户信息
     * @param $phone
     * @return mixed
     */
    protected function get_call_user($phone){

        $user_info = $this->find_user_info_by_phone($phone);
        if(!$user_info){
            $user_info = $this->find_user_info_by_order_phone($phone);
        }
        return $user_info;
    }

    /**
     * 处理用户信息
     * @param $user_info
     * @return array
     */
    protected function get_user_data($user_info){
        $return_data = array(
            'rlt' => 0,
            'data' => array(
                array(
                    'index' => 0,
                    'key' => 'user_id',
                    'label' => '会员ID',
                    'value' => $user_info['user_id'],
                    'href' => $this->host.'users.php?act=list&keyword='.$user_info['user_name'],
                ),
                array(
                    'index' => 1,
                    'key' => 'user_name',
                    'label' => '会员名字',
                    'value' => $user_info['user_name'],
                    'href' => $this->host.'users.php?act=list&keyword='.$user_info['user_name'],
                ),
                array(
                    'index' => 2,
                    'key' => 'mobile_phone',
                    'label' => '绑定手机号',
                    'value' => $user_info['mobile_phone'],
                ),
                array(
                    'index' => 3,
                    'key' => 'user_rank',
                    'label' => '会员级别',
                    'value' => $user_info['user_rank'] == 2?'VIP会员':'注册用户',
                ),
                array(
                    'index' => 4,
                    'key' => 'address1',
                    'label' => '默认地址',
                    'value' => "【姓名】{$user_info['consignee']}【手机】{$user_info['mobile']}【地标】{$user_info['sign_building']}",
                ),
                array(
                    'index' => 5,
                    'key' => 'address2',
                    'label' => '默认地址',
                    'value' => "【地址】{$user_info['address']}",
                ),
            ),
            'modify_cb' => ''
        );

        return $return_data;
    }

    /**
     * 处理订单列表
     * Created By caicm
     * @param $user_id
     * @param $from
     * @return array
     */
    protected function get_order_list($user_id, $from){
        $page_num = 5;
        $order_data = array();

        $order_list = $this->find_order_list($user_id, $from.','.$page_num);

        /* 订单状态 */
        $_LANG = get_order_state();

        foreach ($order_list as $key=>$val){

            $status = $_LANG['os'][$val['order_status']] . ',' . $_LANG['ps'][$val['pay_status']] . ','.$_LANG['cg'][$val['outgo']] . ','.$_LANG['dd'][$val['station']] . ',' . $_LANG['ss'][$val['shipping_status']];

            $order_data[$key]['index'] = $key;
            $blocks = array(
                array(
                    'index' => 0,
                    'is_title' => 'true',
                    'data' => array(
                        array(
                            'index' => 0,
                            'key' => 'order_sn',
                            'label' => '订单号',
                            'value' => $val['order_sn'],
                            'href' => $this->host. 'order.php?act=info&order_id='.$val['order_id'],
                        ),
                    )

                ),
                array(
                    'index' => 1,
                    'data' => array(
                        array(
                            'index' => 1,
                            'key' => 'add_time',
                            'label' => '下单时间',
                            'value' => local_date('Y-m-d H:i', $val['add_time']),
                            'href' => $this->host. 'order.php?act=info&order_id='.$val['order_id'],
                        ),
                        array(
                            'index' => 2,
                            'key' => 'pay_time',
                            'label' => '支付时间',
                            'value' => local_date('Y-m-d H:i', $val['pay_time'])
                        ),
                        array(
                            'index' => 3,
                            'key' => 'order_sn',
                            'label' => '支付方式',
                            'value' => $val['pay_name']
                        ),
                        array(
                            'index' => 4,
                            'key' => 'status',
                            'label' => '订单状态',
                            'value' => $status
                        ),
                        array(
                            'index' => 5,
                            'key' => 'best_time',
                            'label' => '最佳收货时间',
                            'value' => $this->get_best_time($val)
                        ),
                        array(
                            'index' => 6,
                            'key' => 'lite_name',
                            'label' => '物流公司',
                            'value' => $val['lite_name']?$val['lite_name']:'自配送'
                        ),
                        array(
                            'index' => 7,
                            'key' => 'warehouse_name',
                            'label' => '物流点',
                            'value' => $val['warehouse_name'] . "(".$val['deliver_region'].")"
                        ),
                    )
                )
            );

            $order_data[$key]['blocks'] = $blocks;

        }

        return array(
            'rlt' => 0,
            'count' => $page_num,
            'orders' => $order_data
        );
    }

    /**
     * 获取最佳配送时间
     * Created By caicm
     * @param $order
     * @return string
     */
    protected function get_best_time($order){
        if ($order['best_time'] == 0) {
            $order['best_time_2'] = "无期望时间";
        } else {


            if ($order['best_time_start']) {
                $order['best_time_2'] = date('Y-m-d H:i:s', $order['best_time_start']) . "-" . date('Y-m-d H:i:s', $order['best_time']);
            } else {
                if ($order['is_presell'] == 1) {
                    //预售单
                    $order['best_time_2'] = date('Y-m-d' . " 10:00:00", $order['best_time']) . "  -   " . date('Y-m-d' . " 20:30:00", $order['best_time']);
                } else {
                    if ($order['shipping_id'] == 2) {
                        //自提订单
                        $order['best_time_2'] = date('Y-m-d' . " 10:00:00", $order['best_time']) . "  -   " . date('Y-m-d' . " 20:30:00", $order['best_time']);
                    } else {
                        $order['best_time_2'] = date('Y-m-d H:i:s', $order['best_time'] - 7199) . "  -   " . date('Y-m-d H:i:s', $order['best_time'] + 1);
                    }
                }
            }
        }
        return $order['best_time_2'];
    }

    /**
     * 获取订单列表
     * Created By caicm
     * @param string $openid
     * @param string $limit
     * @return mixed
     */
    protected function find_order_list($openid = '', $limit = ''){
        if(is_numeric($openid)){
            $where = array(
                'o.user_id' => $openid
            );
        }else{
            $where = array(
                'w.openid' => $openid
            );
        }

        $field = 'o.pay_name,
                o.order_id,
                o.order_sn,
                o.add_time,
                o.pay_time,
                o.order_status,
                o.pay_status,
                o.outgo,
                o.station,
                o.shipping_status,
                o.best_time_start,
                o.best_time,
                o.shipping_id,
                dc.lite_name,
                dr.name as deliver_region,
                zc.name as warehouse_name';

        return M('order_info as o')
            ->field($field)
            ->join('left join sdx_wechat_user as w on o.user_id = w.ect_uid')
            ->join('left join sdx_distribution_company as dc on o.distribution_company_id = dc.id')
            ->join('left join sdx_warehouse_deliver_region as dr on o.wdr_id = dr.id')
            ->join('left join sdx_zoning_cate as zc on dr.zoning_id = zc.id')
            ->where($where)
            ->limit($limit)
            ->order('o.order_id desc')
            ->select();
    }

    /** 获取用户信息
     * Created By caicm
     * @param string $openid
     * @return mixed
     */
    protected function find_user_info($openid = ''){
        if(is_numeric($openid)){
            $where = array(
                'u.user_id' => $openid
            );
        }else{
            $where = array(
                'w.openid' => $openid
            );
        }
        return M('wechat_user as w')
            ->field('u.user_id,u.user_name,u.mobile_phone,u.user_rank,a.consignee,a.mobile,a.sign_building,a.address')
            ->join('left join sdx_users as u on w.ect_uid=u.user_id')
            ->join('left join sdx_user_address as a on u.user_id=a.user_id and a.default=1')
            ->where($where)
            ->find();
    }

    /** 获取用户信息
     * Created By caicm
     * @param $phone
     * @return mixed
     */
    protected function find_user_info_by_phone($phone = ''){
        $where = array(
            'u.mobile_phone' => $phone
        );

        return M('users as u')
            ->field('u.user_id,u.user_name,u.mobile_phone,u.user_rank,a.consignee,a.mobile,a.sign_building,a.address')
            ->join('left join sdx_user_address as a on u.user_id=a.user_id and a.default=1')
            ->where($where)
            ->find();
    }

    /** 获取用户信息
     * Created By caicm
     * @param $phone
     * @return mixed
     */
    protected function find_user_info_by_order_phone($phone = ''){
        $where = array(
            'o.mobile' => $phone
        );

        return M('order_info as o')
            ->field('u.user_id,u.user_name,u.mobile_phone,u.user_rank,a.consignee,a.mobile,a.sign_building,a.address')
            ->join('left join sdx_users as u on o.user_id=u.user_id')
            ->join('left join sdx_user_address as a on u.user_id=a.user_id and a.default=1')
            ->where($where)
            ->find();
    }

    /**
     * token验证
     * Created By caicm
     * @param string $appid
     * @param string $appsecret
     * @param string $token
     */
    protected function check_token($appid='', $appsecret='', $token=''){
        if($appid && $appid != $this->appid){
            returnApiError('a参数有误');
        }
        if($appsecret && $appsecret != $this->appsecret){
            returnApiError('s参数有误');
        }
        if($token && $token != $this->token){
            returnApiError('t参数有误');
        }
    }

    /**
     * 返回josn 数据
     * Created By caicm
     * @param array $data
     * @return string
     */
    protected function return_json($data = array()){
        $json = json_encode($data);
        //write_log($json , 'yukf');
        echo $json; exit;
    }



}